Distribute coins in binary tree [DFS]¶
Time: O(N); Space: O(H); medium
Given the root of a binary tree with N nodes, each node in the tree has node.val coins, and there are N coins total.
In one move, we may choose two adjacent nodes and move one coin from one node to another. (The move may be from parent to child, or from child to parent.)
Return the number of moves required to make every node have exactly one coin.
Example 1:
Input: root = {TreeNode} [3,0,0]
Output: 2
Explanation:
From the root of the tree, we move one coin to its left child, and one coin to its right child.
Example 2:
Input: root = {TreeNode} [0,3,0]
Output: 3
Explanation:
From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.
Example 3:
Input: root = {TreeNode} [1,0,2]
Output: 2
Example 4:
Input: root = {TreeNode} [1,0,0,null,3]
Output: 4
Constraints:
1<= N <= 100
0 <= node.val <= N
[5]:
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
1. Depth First Search¶
Intuition
If the leaf of a tree has 0 coins (an excess of -1 from what it needs), then we should push a coin from its parent onto the leaf.
If it has say, 4 coins (an excess of 3), then we should push 3 coins off the leaf.
In total, the number of moves from that leaf to or from its parent is excess = Math.abs(num_coins - 1).
Afterwards, we never have to consider this leaf again in the rest of our calculation.
Algorithm
We can use the above fact to build our answer.
Let dfs(node) be the excess number of coins in the subtree at or below this node: namely, the number of coins in the subtree, minus the number of nodes in the subtree.
Then, the number of moves we make from this node to and from its children is abs(dfs(node.left)) + abs(dfs(node.right)).
After, we have an excess of node.val + dfs(node.left) + dfs(node.right) - 1 coins at this node.
[6]:
class Solution1(object):
"""
Time: O(N)
Space: O(H)
"""
def distributeCoins(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(root, result):
if not root:
return 0
left, right = dfs(root.left, result), dfs(root.right, result)
result[0] += abs(left) + abs(right)
return root.val + left + right - 1
result = [0]
dfs(root, result)
return result[0]
[7]:
s = Solution1()
root = TreeNode(3)
root.left = TreeNode(0)
root.right = TreeNode(0)
assert s.distributeCoins(root) == 2
root = TreeNode(0)
root.left = TreeNode(3)
root.right = TreeNode(0)
assert s.distributeCoins(root) == 3
root = TreeNode(1)
root.left = TreeNode(0)
root.right = TreeNode(2)
assert s.distributeCoins(root) == 2
root = TreeNode(1)
root.left = TreeNode(0)
root.right = TreeNode(0)
root.right.right = TreeNode(3)
assert s.distributeCoins(root) == 4
See also:¶
https://leetcode.com/problems/distribute-coins-in-binary-tree
https://www.lintcode.com/problem/distribute-coins-in-binary-tree/description